﻿#include "ssActorThread.h"
#include "ssActorMgr.h"
#include "thread/threadLock/ssThreadCondition.h"


namespace StarSeeker
{

ssActorThread::ssActorThread(ssActorMgr& pool)
	:m_threadId(-1),m_weight(0),m_pool(pool)
{
}

ssActorThread::~ssActorThread()
{
	RequestStop();
	WaitForExit();
}

void ssActorThread::ThreadMemberFunc()
{
	OnThreadRun();
	while (!IsRequestStop())
	{
		ssActor* pActor = 0;

		SS_MUTEX_LOCK(m_pool.m_mutex); //锁定互斥量
		while (m_pool.GetPendingCount()==0 && !IsRequestStop())
		{
			m_pool.m_condGet.Wait(); //条件变量等待
		}
		pActor = m_pool.PopPendingActor();
		SS_MUTEX_UNLOCK(m_pool.m_mutex);

		if (pActor)
		{
			ulint total = pActor->m_msgList.Count();
			if (total>0)
			{
				++pActor->m_working;
				ulint count = 1;
				ssMsg_s msg;
				if (m_weight >= 0)
				{
					count = total >> m_weight;
				}
				for (ulint i = 0; i < count; ++i)
				{
					if (pActor->PopMsg(msg))
					{
						pActor->HandleMsg(msg);
					}
				}
				if (pActor->m_msgList.Count() > 0)
				{
					SS_MUTEX_LOCK(m_pool.m_mutex);
					m_pool.PushPendingActor(pActor->GetID());
					SS_MUTEX_UNLOCK(m_pool.m_mutex);
				}
				--pActor->m_working;
			}
		}
	}
}

}
